package net.loyin.app.ctrl.admin;

import com.jfinal.aop.Clear;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.ehcache.CacheKit;
import net.loyin.ext.annotation.ControllerBind;
import net.loyin.ext.annotation.CtrlMethod;
import net.loyin.app.Constant;
import net.loyin.app.model.SysMenu;
import net.loyin.app.model.SysUser;
import net.loyin.utils.encrypt.DESUtils;
import org.apache.commons.lang.StringUtils;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.*;

/**
 * 管理后台
 * Created by loyin on 16/1/12.
 */
@ControllerBind(route = "/admin")
public class AdminCtrl extends AdminBaseCtrl {
    private static boolean useCaptcha = true;

    @Clear
    public void index() {
        if (StringUtils.isNotBlank(this.getUserId())) {
            this.redirect("/admin/main");
        }
        useCaptcha = PropKit.use(Constant.SYSTEM).getBoolean("system_admin_captcha", true);
        this.setAttr("useCaptcha", useCaptcha);
        String para=this.getPara(0);
        if(StringUtils.isNotBlank(para)){
            this.renderHtml("<h1>未找到/"+para+"</h1>");
        }
    }

    public void dashboard() {

    }

    @Clear
    public void login() {
        String username = this.getPara("username");
        String password = this.getPara("password");
        String vcode = this.getPara("vcode");
        String captcha_code = this.getCookie("_jfinal_captcha");
        this.removeCookie("_jfinal_captcha");
        if (useCaptcha)
            if (StrKit.isBlank(captcha_code)) {
                this.renderJsonMsg(this.JSON_RESULT_WARNNING,"验证码超时!请刷新验证码.");
                return;
            }
        if (useCaptcha)
            if (StrKit.isBlank(vcode)) {
                this.renderJsonMsg(this.JSON_RESULT_WARNNING,"验证码不能为空!");
                return;
            }
        if (StrKit.isBlank(username)) {
            this.renderJsonMsg(this.JSON_RESULT_WARNNING,"用户名不能为空!");
            return;
        }
        if (StrKit.isBlank(password)) {
            this.renderJsonMsg(this.JSON_RESULT_WARNNING,"密码不能为空!");
            return;
        }
        if (useCaptcha)
            if (StringUtils.isNotBlank(vcode) && StringUtils.isNotBlank(captcha_code)) {
                if (captcha_code.equals(HashKit.md5(vcode.toUpperCase())) == false) {
                    this.renderJsonMsg(this.JSON_RESULT_WARNNING,"验证码错误!");
                    return;
                }
            }
        DESUtils desUtils = new DESUtils();
        SysUser user = SysUser.dao.login(username, desUtils.encryptString(password));
        if (user == null) {
            this.renderJsonMsg(this.JSON_RESULT_WARNNING,"用户名和密码不匹配!");
            return;
        } else {
            String userid = user.getId();
            user.clear();
            user.setId(userid);
            user.setLastLoginTime(new Date());
            user.setLastLoginIp(this.getRemortIP());
            user.update();
            this.setCookie(PropKit.get(Constant.LOGIN_COOKIE_KEY), desUtils.encryptString(userid), 86400);//一天的有效期
            this.renderJsonMsg(this.JSON_RESULT_SUCCESS,null);
            return;
        }
    }

    @Clear
    public void logout() {
        try {
            this.removeCookie(PropKit.get(Constant.LOGIN_COOKIE_KEY));
        } catch (Exception e) {
        }
        this.redirect("/admin");
    }
    /**登录超时*/
    @Clear
    public void timeOut(){
    }
    /**无权限*/
    @Clear
    public void noPermission(){
    }
    public void main() {
        if (StringUtils.isBlank(this.getUserId())) {
            this.redirect("/admin");
            return;
        }
        this.setAttr("menuList", SysMenu.dao.getAuthMenu(this.getUserId()));
    }

    /**
     * 验证码图片
     */
    @Clear
    public void captcha() {
        this.renderCaptcha();
    }

    /***
     * 清除缓存
     */
    @CtrlMethod(isAjax = true)
    public void clearCache() {
        CacheKit.remove(this.getPara(0), this.getPara(1));
    }

    public void system(){
        Prop prop=PropKit.use(Constant.SYSTEM);
        Properties ps= prop.getProperties();
        if(ps!=null){
            Enumeration e= ps.propertyNames();
            Map<String,Object> data=new HashMap<String,Object>();
                String key=null;
                while (e.hasMoreElements()){
                    key=(String)e.nextElement();
                    data.put(key,prop.get(key));
                }
            this.setAttr("data",data);
        }
    }
    @CtrlMethod(isAjax = true)
    public void saveSystemSet(){
        PropKit.useless(Constant.SYSTEM);
        Prop prop=PropKit.use(Constant.SYSTEM);
        Properties ps= prop.getProperties();
        if(ps!=null){
            Enumeration e= ps.propertyNames();
            StringBuffer line=new StringBuffer();
            String key=null;
            while (e.hasMoreElements()){
                key=(String)e.nextElement();
                line.append(key);
                line.append("=");
                String para=this.getPara(key);
                if(StringUtils.isNotBlank(para)) {
                    line.append(para);
                }else{
                    line.append(prop.get(key));
                }
                line.append("\n");
            }
            URL url=Thread.currentThread().getContextClassLoader().getResource("/"+Constant.SYSTEM);
            try {
                OutputStreamWriter otw=new OutputStreamWriter(new FileOutputStream(url.getFile()),"UTF-8");
                BufferedWriter bw=new BufferedWriter(otw);
                bw.write(line.toString());
                bw.flush();
                bw.close();
                PropKit.useless(Constant.SYSTEM);
                PropKit.use(Constant.SYSTEM);
            }catch (Exception ex){
                logger.error("保存异常",ex);
                this.renderJsonMsg(JSON_RESULT_ERROR,"保存系统设置异常!");
                return;
            }
        }
        this.renderJsonMsg(JSON_RESULT_SUCCESS,"保存系统设置成功!");
    }
}
